<template>
  <div class="approval-detail">
    <div class="type-select" style="margin-top: 2vh">
      <el-input
          v-model="searchKey"
          placeholder="搜索审批项"
          style="width: 300px; margin-bottom: 20px"
          clearable
      /><el-button type="primary" :disabled="searchKey===''" style="margin-bottom: 20px" @click="getApproval(0)">搜索</el-button>
      <div style="float: right">
        <el-button style="margin-bottom: 20px" @click="getApproval(0)">我的审批项</el-button>
        <el-button type="danger" style="margin-bottom: 20px" @click="getApproval(1)">待操作审批项</el-button>
      </div>
      <el-table
          :data="approvalData"
          highlight-current-row
          style="width: 100%;border-radius: 10px"
      >
        <el-table-column prop="id" label="审批项ID" width="300px"></el-table-column>
        <el-table-column prop="processName" label="审批项名" width="180">
          <template #default="{row}">
            <div class="type-tag">
              <el-tag :type="tagTypeMap[row.type]">
                {{ labelMap[row.type] }}
              </el-tag>
              {{ row.processName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="approvalName" label="审批发起人" width="120"/>
        <el-table-column prop="steps" label="审批步骤" width="120">
          <template #default="{row}">
            <el-tag>{{ row.stepNumber }}/{{row.currentStep}}步骤</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <template  #default="{row}">
            <el-button v-if="row.approvalId!==userInfo.info.id" style="" @click="toApproval2(row)">操作审批</el-button>
            <el-button v-if="row.approvalId===userInfo.info.id" style="" @click="startA(row)">修改审批</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          v-model:page-size="pageSize"
          v-model:current-page= "pageCount"
          @change="getApproval"
          class="mt-4"
          style="display: flex; justify-content: center;margin-top: 2vh"
      />
    </div>
    <el-dialog
        v-model="inApproval"
        :title="num.processName"
        width="1000"
        :before-close="handleClose"
    >
      <el-steps style="max-width: 100%;" :active="100">
        <el-step :title="appUser[index]"  v-for="(a,index) in num.currentStep"></el-step>
      </el-steps>
      <div  class="approval-form">
        <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-width="100px"
        >
          <el-form-item label="审批事由" prop="title">
            <el-input
                v-model="formData.title"
                placeholder="请输入个人审批情况"
            />
          </el-form-item>

          <!-- 动态表单字段 -->
          <template v-for="(field, index) in num.approvalItem?.controls" :key="index">
            <el-form-item
                :label="labelMap2[field]"
                prop="items"
                :rules="formRules"
            >
              <!-- 文本输入 -->
              <el-input
                  v-if="field === 'text'"
                  v-model="formData.fields.text"
                  :placeholder="field.placeholder"
              />

              <!-- 数字输入 -->
              <el-input-number
                  v-else-if="field === 'number'"
                  v-model="formData.fields.number"
                  :precision="field.precision || 0"
                  :min="field.min || 0"
              />

              <!-- 日期范围 -->
              <el-date-picker
                  v-else-if="field === 'daterange'"
                  v-model="formData.fields.daterange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
              />

              <!-- 文件上传 -->

              <el-upload
                  v-else-if="field === 'file'"
                  class="upload-demo"
                  :auto-upload="false"
                  :on-change="handleFileChange"
                  v-model:file-list="fileList"
                  :show-file-list="true"
                  multiple
                  style="width: 100%"
                  :on-remove="(file, fileList) => handleRemove(file)"
              >
                <el-button type="primary">点击上传</el-button>
                <template #tip>
                  <div class="el-upload__tip" style="color:rosybrown;">
                    {{ field.tip || '删除文件会直接修改审批信息，请谨慎删除' }}
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </template>

          <el-form-item label="发起审批说明" prop="description">
            <el-input
                v-model="formData.description"
                type="textarea"
                :rows="4"
                placeholder="请输入详细说明"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :disabled="isSub()" @click="todef('提交')">立即提交</el-button>
            <el-button @click="todef('重置')">重置</el-button>
            <el-button type="warning" @click="todef('撤回')">撤回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog
        v-model="apptovalType"
        :title="'是否'+types"
        width="500"
        :before-close="handleClose"
    >
      <template #footer>
        <div class="dialog-footer" style="align-items: center">
          <el-button @click="apptovalType = false">取消</el-button>
          <el-button v-if="types==='提交'" type="primary" @click="submitForm()">
            确定
          </el-button>
          <el-button v-if="types==='重置'" type="primary" @click="resetForm">
            确定
          </el-button>
          <el-button v-if="types==='撤回'" type="primary" @click="reForm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
        v-model="inApproval2"
        width="1000"
        :before-close="handleClose"
    >
      <!-- 审批概览 -->
      <el-card class="overview-card">
        <div class="overview-header">
          <h2>{{ nums.processName }}</h2>
          <el-tag :type="statusTypeMap[nums.status]" effect="dark">
            {{ statusTextMap[nums.status] }}
          </el-tag>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="审批编号">
            {{ nums.processId }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ dayjs(nums.createTime).format('YYYY-MM-DD HH:mm') }}
          </el-descriptions-item>
          <el-descriptions-item label="申请人">
            {{ nums.approvalName }}
          </el-descriptions-item>
          <el-descriptions-item label="审批类型">
            <el-tag type="primary">
              {{nums.processName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审批要求">
            {{nums.requirement}}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 审批进度 -->
      <el-card class="progress-card">
        <template #header>
          <div class="card-title">审批进度</div>
        </template>
        <el-steps direction="vertical" :active="3">
          <el-step
              v-for="(step, index) in approvalRecord"
              :key="index"
              :title="step.title"
              :status="step.status">
            <template #description>
              <div class="step-detail">
                <div v-if="step.approveId===userInfo.info.id">处理人：本人</div>
                <div v-else>处理人：{{ step.approveName }}</div>
                <div v-if=" step.comment!==null">审批意见：{{ step.comment }}</div>
                <div v-if="step.comment!==null">处理时间：{{step.approveTime }}</div>
              </div>
            <div class="action-buttons" v-if="step.approveId===userInfo.info.id">
              <el-input style="margin-bottom: 2vh"  type="textarea" placeholder="请输入审批意见"  v-model="comments"></el-input>
              <div style="display: flex; justify-content: center;">
              <el-button type="primary" @click="isApproval(step.id,0)">同意</el-button>
              <el-button type="danger" @click="isApproval(step.id,1)">驳回</el-button>
              </div>
            </div>
            </template>
          </el-step>
        </el-steps>
      </el-card>
      <el-dialog
          v-model="nextStep"
          :title="'确认'+titles"
          width="500"
          @before-close="nextStep = false"
      >
        <el-button type="primary" @click="handleApprove()">确认</el-button>
        <el-button type="danger" @click="nextStep=false">取消</el-button>
      </el-dialog>
      <!-- 审批表单数据 -->
      <el-card class="form-data-card">
        <template #header>
          <div class="card-title">申请信息</div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="审批事由">
            {{ nums.formData.title }}
          </el-descriptions-item>

          <template v-for="(value, key) in nums.formData.fields" :key="key">
            <el-descriptions-item :label="fieldLabelMap[key]" v-if="key === 'daterange' && nums.formData.fields.daterange!==''">
                <el-date-picker
                    v-model="nums.formData.fields.daterange"
                    type="datetimerange"
                    start-placeholder="Start date"
                    end-placeholder="End date"
                    format="YYYY-MM-DD HH:mm:ss"
                    date-format="YYYY/MM/DD ddd"
                    time-format="A hh:mm:ss"
                    readonly="true"
                />
            </el-descriptions-item>
            <el-descriptions-item :label="fieldLabelMap[key]" v-if="key === 'file' && nums.formData.fields.file!==''">
                <div class="el-upload__tip" v-for="(name,index) in nums.formData.fields.file">
                   <el-link type="warning" @click="loadFile(name)">{{name.name.split('/').pop()}}</el-link>
                </div>
            </el-descriptions-item>
            <el-descriptions-item :label="fieldLabelMap[key]" v-if="key === 'text' && nums.formData.fields.text!==''">
                {{ nums.formData.fields.text}}
            </el-descriptions-item>
              <el-descriptions-item :label="fieldLabelMap[key]" v-if="key === 'number' && nums.formData.fields.number!==''">
                {{ nums.formData.fields.number}}
              </el-descriptions-item>
          </template>

          <el-descriptions-item label="详细说明">
            {{ nums.formData.description }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </el-dialog>

  </div>
</template>

<script setup>
import {ref, computed, reactive, onMounted} from 'vue'
import { useRoute } from 'vue-router'
import {getUnderwayApproval, updateApproval} from "@/api/AStartApproval.js";
import useUserInfoStore from "@/stores/userInfo.js";
import {getUserName} from "@/api/user.js";
import {getApprovals, getConfigInfo} from "@/api/Approval.js";
import {initiateApproval} from "@/api/AInstance.js";
import {ElMessage} from "element-plus";
import dayjs from "dayjs";
import {getRecord, retrieveApproval, setApproval} from "@/api/record.js";
import {getToken} from "@/api/load.js";
import OSS from "ali-oss";
const selectedType = ref(null)
const searchKey = ref('')
const formData = ref({
  title:'',
  description:'',
  fields: {
    dateRange: '',
    text:'',
    file:'',
    number:'',
  }
})
const fileList = ref([])
const userInfo = useUserInfoStore()
const approvalData = ref('')
const filteredApprovalTypes = computed(() => {
  return detailData.value.filter(item =>
      item.title.includes(searchKey.value) ||
      item.description.includes(searchKey.value)
  )
})
const formRules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入说明', trigger: 'blur' }],
})
// 重置表单
const resetForm = () => {
  selectedType.value = null
  formData.value.fields={}
  formData.value.title= ''
  formData.value.description= ''
  apptovalType.value = ref(false)
}
const types = ref()

const comments = ref()
// 模拟审批详情数据
const detailData = ref([{}])
const total = ref(1)
const pageSize = ref(4)
const pageCount = ref(Math.ceil(total.value / pageSize.value))
const getApproval = async (type) => {
  let res = await getUnderwayApproval(userInfo.info.id,searchKey.value,pageCount.value,pageSize.value,type)
  if (res.total!==undefined && res.total!==0){
    total.value = res.total
  }
  approvalData.value = res.list
}
getApproval(0)
// 状态类型映射
const statusTypeMap = {
  0: 'info',
  1: 'warning',
  2: 'success',
  3: 'danger'
}

const statusTextMap = {
  'RETRIEVE': '已撤回',
  'PENDING': '审批中',
  'APPROVED': '已通过',
  'REJECTED': '已驳回'
}
const options3 = [{value: 1, label: '财务'},{value: 2, label: '人事'},{value: 3, label: '行政'}]
const options4 =  [{value: 'text', label: '文本输入'},{value: 'daterange', label: '时间'},{value: 'file', label: '文件'},{value: 'number', label: '数字'}]
const tagTypeMap = {
  1: 'success',
  2: 'warning',
  3: 'info'
}
const labelMap = Object.fromEntries(
    options3.map(item => [item.value, item.label])
);
const reForm = async ()=>{
  try {
    let res = await retrieveApproval(num.value.id)
    ElMessage.success(res)
    handleClose()
  }catch(error){
    ElMessage.error(error.message);
  }
}
const inApproval = ref(false)
const inApproval2 = ref(false)
const nums = ref()

const num = ref({processName: "a"})
let appUser = ref([])
const getApprovalInfo = async (pid,id) => {
  let approval = await getConfigInfo(pid)
  if (approval !== undefined){
    num.value = approval
  }
  num.value.id = id
}
const labelMap2 = Object.fromEntries(
    options4.map(item => [item.value, item.label])
);
const upId = ref()
const startA =async (row) => {
  await getApprovalInfo(row.processId,row.id)
  formData.value = JSON.parse(row.formData)
  upId.value = row.id
  for (let i = 0; i < num.value.approvalSteps?.length; i++) {
    await getUserName(num.value.approvalSteps[i]?.approvePeople).then(result => {
      appUser.value[i] = num.value.approvalSteps[i]?.approveType + "/" + result
    })
  }
  fileList.value = formData.value.fields.file
  inApproval.value = true;
}
const isSub=()=>{
  // 第一部分验证
  if (!formData.value.title || !formData.value.description) {
    return true;
  }
  // 第二部分动态字段验证
  return num.value.approvalItem.controls.every(item => {
    // 使用方括号语法访问动态属性
    return String(formData.value.fields[item] || '').trim() === ''
  });
}
const toApproval2= (row)=>{
  inApproval2.value=true;
  getApprovalRecord(row.id)
  nums.value= row
}
const nextStep = ref(false)
const titles = ref('')
const decks = ref(0)
const approveId = ref(0)
const isApproval = (id,dec)=>{
  if (dec===0){
    titles.value = '通过'
  }else if(dec===1){
    titles.value = '驳回'
  }
  decks.value = dec
  approveId.value = id
  nextStep.value = true
}
const handleApprove = async () => {
  if (comments.value===''){
    ElMessage.error("请输入审批意见")
    return
  }
  let decision
  if (decks.value===0){
    decision = "approved"
  }else {
    decision = "rejected"
  }
  try {
    let res = await setApproval(approveId.value,nums.value.id,decision,comments.value)
    ElMessage.success(res)
    inApproval2.value=false
    nextStep.value = false
    await getApproval(1)
    decks.value = 0
    approveId.value = ''
    comments.value=ref('')
  }catch (err){
    ElMessage.error(err)
  }
}
const todef = (type)=>{
  types.value = type
  apptovalType.value = true
}
const apptovalType = ref(false)
const handleWithdraw = () => {
  // 撤回逻辑
}
const submitForm = async () => {
  formData.value.fields.file = fileList.value
  let res = await updateApproval(upId.value,JSON.stringify(formData.value))
  if (res==='更新成功') {
    apptovalType.value = ref(false)
    ElMessage.success(res)
    num.value = ''
    inApproval.value = false
    apptovalType.value = false
    await getApproval(0);
  }else {
    ElMessage.error('修改失败')
  }
}
// 字段标签映射
const fieldLabelMap = {
  text: '信息描述',
  number: '数值',
  daterange: '时间范围',
  file: '附件材料'
}
const approvalRecord = ref()
const getApprovalRecord = async (id) => {
  let decision = null
  approvalRecord.value = await getRecord(id,decision)
  nums.value.formData = JSON.parse(nums.value.formData)
}
const getSTSToken = async () => {
  return await getToken();
};

const initOSSClient = async () => {
  let credentials = await getSTSToken();
  return new OSS({
    region: 'oss-cn-hangzhou',
    accessKeyId: credentials.AccessKeyId,
    accessKeySecret: credentials.AccessKeySecret,
    stsToken: credentials.SecurityToken,
    bucket: 'web-framework10011',
    endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
    secure: true
  });}
// 文件上传处理
const handleFileChange = async (uploadFile) => {
  try {
    const client = await initOSSClient()
    const ossPath = `在线审批系统/${uploadFile.raw.uid}_${uploadFile.name}`

    // 执行上传
    const result = await client.put(ossPath, uploadFile.raw)
    ElMessage.success('上传成功')
  } catch (err) {
    ElMessage.error('上传失败')
    console.error('OSS Error:', err)
  }
}
// 文件下载
const loadFile = async (file) => {
  try {
    let names = `${file.name}`
    const client = await initOSSClient();
    // 生成带签名的下载链接（1小时有效）
    const url = client.signatureUrl(names, {
      expires: 3600, // 有效期1小时（单位：秒）
      response: {
        'content-disposition': 'attachment' // 强制浏览器下载
      }
    });

    // 提取原始文件名（去除路径和时间戳）
    const fileNameWithTimestamp = names.split('/').pop();
    const originalFileName = fileNameWithTimestamp.split('_').slice(1).join('_');
    // 创建虚拟链接触发下载
    const link = document.createElement('a');
    link.href = url;
    link.download = originalFileName; // 设置下载文件名
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success('开始下载');
  } catch (err) {
    ElMessage.error('下载失败');
    console.error('Download Error:', err);
  }
};
// 文件删除
const handleRemove = async (file) => {
  try {
    file.name = `在线审批系统/${file.raw.uid}_${file.name}`
    const client = await initOSSClient()
    await client.delete(file.name)
    await submitForm()
    // 更新文件列表
    fileList.value = fileList.value.filter(f => f.uid !== file.uid)
    ElMessage.success('删除成功')
  } catch (err) {
    ElMessage.error('删除失败')
    console.error('Delete Error:', err)
  }
}
const handleClose  = ()=>{
  inApproval.value = false
  apptovalType.value = false
  getApproval(0)
}
</script>

<style scoped>
.approval-detail {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.overview-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}
.card-title {
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.step-detail {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  line-height: 1.8;
}
</style>